import 'package:flutter/material.dart';
import 'package:flutter_novel/config/invoke_manager.dart';
import 'package:flutter_novel/config/use_channels.dart';
import 'package:flutter_novel/detail/bloc/home_detail_bloc.dart';
import 'package:flutter_novel/detail/bloc/home_detail_event.dart';
import 'package:flutter_novel/detail/bloc/home_detail_state.dart';
import 'package:flutter_novel/detail/data/model/detail_model_entity.dart';
import 'package:flutter_novel/detail/widget/app_bar_content.dart';
import 'package:flutter_novel/detail/widget/bottom_content_widget.dart';
import 'package:flutter_novel/detail/widget/des_widget.dart';
import 'package:flutter_novel/detail/widget/indication_widget.dart';
import 'package:flutter_novel/detail/widget/novel_header_widget.dart';
import 'package:flutter_novel/detail/widget/recommend_widget.dart';
import 'package:flutter_novel/detail/widget/series_widget.dart';
import 'package:flutter_novel/routers/navigator_utils.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:status_bar_control/status_bar_control.dart';
import '../../../base/base_stateful_page.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

class HomeDetailPage extends BasePage {
  final String imageUrl;
  const HomeDetailPage({super.key, required this.imageUrl});

  @override
  BasePageState<BasePage> getState() => _HomeDetailPageState();
}

class _HomeDetailPageState extends BasePageState<HomeDetailPage> {
  String _imageUrl = '';

  @override
  void initState() {
    super.initState();
    pageBackgroundColor = Colors.white;
    showAppBar = false;
    appBarTitle = "详情";
    _initParameters();
  }

  @override
  void onBuildComplete() {
    super.onBuildComplete();
    context.read<HomeDetailBloc>().add(GetDetailDataEvent());
  }

  void _initParameters() {
    UseChannel.parametersChannel.setMethodCallHandler((call) async {
      if (call.method == 'initialParams') {
        _imageUrl = Map<dynamic, dynamic>.from(call.arguments)['imageUrl'];
      } else if (call.method == 'nativePop') {
        if (NavigatorUtils.canPop(context)) {
          NavigatorUtils.pop(context);
        } else {
          InvokeManager.popPage();
        }
      }
    });
  }

  /// 构建列表内容
  Widget _buildListContent() {
    return BlocBuilder<HomeDetailBloc, HomeDetailState>(
      buildWhen: (cur, pre) => cur.loadFinish != pre.loadFinish,
      builder: (context, state) {
        return NotificationListener<ScrollNotification>(
          onNotification: (notification) {
            context.read<HomeDetailBloc>().add(
              UpdateOffsetEvent(newOffset: notification.metrics.pixels),
            );
            double alpha = notification.metrics.pixels / 100;
            if (alpha == 0) {
              StatusBarControl.setStyle(StatusBarStyle.LIGHT_CONTENT);
            } else if (alpha == 1) {
              StatusBarControl.setStyle(StatusBarStyle.DARK_CONTENT);
            }
            return false;
          },
          child: ListView(
            physics: const ClampingScrollPhysics(),
            padding: EdgeInsets.only(bottom: statusBarHeight + kToolbarHeight),
            children: [
              NovelHeaderWidget(model: state.detailModelData, imageUrl: _imageUrl),
              DesWidget(model: state.detailModelData),
              SeriesWidget(seriesList: state.seriesList),
              RecommendWidget(list: state.recommendList),
            ],
          ),
        );
      },
    );
  }

  /// 构建自定义导航栏
  Widget _buildAppBar() {
    HomeDetailState state = context.read<HomeDetailBloc>().state;
    return Positioned(
      top: 0,
      left: 0,
      right: 0,
      child: AnimatedOpacity(
        opacity: state.alpha ?? 0,
        duration: const Duration(milliseconds: 100),
        child: Container(
          height: statusBarHeight + kToolbarHeight,
          padding: EdgeInsets.only(top: statusBarHeight),
          decoration: BoxDecoration(
            color: Colors.white,
            border: Border(
              bottom: BorderSide(width: 1.h, color: Colors.black12),
            ),
          ),
          child: AppBarContent(
            detailModel: state.detailModelData,
            scrollOffset: state.scrollOffset ?? 0,
            appBarAlpha: state.alpha ?? 0,
          ),
        ),
      ),
    );
  }

  /// 构建底部控件
  Widget _buildBottomWidget(DetailModelData? detailModelData) {
    if (detailModelData == null) return SizedBox();
    return BlocBuilder<HomeDetailBloc, HomeDetailState>(
      buildWhen: (cur, pre) => cur.loadFinish != pre.loadFinish,
      builder: (context, state) {
        return Positioned(
          left: 0,
          right: 0,
          bottom: 0,
          child: BottomContentWidget(epList: detailModelData.ep),
        );
      },
    );
  }

  Widget _indication() {
    return IndicationWidget();
  }

  @override
  Widget buildPage(BuildContext context) {
    return BlocBuilder<HomeDetailBloc, HomeDetailState>(
      builder: (context, state) {
        if (state.loadFinish != true) {
          return SizedBox();
        }
        return Stack(
          children: [
            _buildListContent(),
            _buildAppBar(),
            _buildBottomWidget(state.detailModelData),
            _indication(),
          ],
        );
      },
    );
  }
}
